package com.wang.yupao.job;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.yupao.model.domain.User;
import com.wang.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户信息  缓存预热
 * 将重要数据定时存入redis中，之后读取比mysql会更快
 */
@Component
@Slf4j
public class ProCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    //主要缓存数据
    // 1L 为主要用户去缓存数据，而不是为所有用户都缓存数据
    private List<Long> mainUserList = Arrays.asList(1L);

    private RedissonClient redissonClient;

    //定时任务 每天的23点59分运行一次
    @Scheduled(cron = "0 59 23 * * *")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("yupao:precachejob:docache:lock");//name: 锁的名字
        try {
            //过期时间
            /**
             * 想要触发Redisson看门狗机制，不能自定义 leaseTime（或者传参 -1）
             * Redisson默认加锁30秒，每隔10秒刷新加锁时间
             * watchdog的延时时间 可以由 lockWatchdogTimeout指定默认延时时间，但是不要设置太小
             * Redisson是通过Future和Timeout功能来实现异步延时
             */
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                for (Long userId : mainUserList) {
                    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                    Page<User> pageUser = userService.page(new Page<>(1, 20), queryWrapper);
                    List<User> userPageRecords = pageUser.getRecords();
                    String redisKey = String.format("yupao:user:recommend:%s", userId);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    //写缓存
                    try {
                        //因为是预热缓存，所以不能设置过期时间
                        //往缓存里存了20条数据
                        valueOperations.set(redisKey, JSONUtil.toJsonStr(userPageRecords), 1, TimeUnit.DAYS);
                    } catch (Exception e) {
                        log.error("redis PreCache set key error", e);
                    }
                }
                log.info("缓存预热。。。");
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error: {}", e);
            throw new RuntimeException(e);
        } finally {
            //释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }


    }
}
